﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Reflection;

namespace UtilLib
{
    public static class XmlUtil
    {
        public static string Serialize<T>(List<T> list, XmlTextWriter writer)
        {
            Type type = typeof(T);
            writer.Formatting = Formatting.Indented;
            writer.Indentation = 4;
            writer.WriteStartDocument(true);
            writer.WriteStartElement(type.Name);
            list.ForEach(k =>
                    {
                        writer.WriteStartElement("Item");
                        PropertyInfo[] properties = type.GetProperties();
                        foreach (PropertyInfo property in properties)
                        {
                            if (property.GetCustomAttributes(typeof(StoreAttribute), true).Count() > 0 &&
                                property.GetValue(k, null) != null)
                            {
                                writer.WriteAttributeString(property.Name, property.GetValue(k, null).ToString());

                            }
                        }
                    });
            return "";
        }
        public static string Serialize<T>(T item, XmlTextWriter writer)
        {
            Type type = typeof(T);

            writer.Formatting = Formatting.Indented;
            writer.Indentation = 4;
            writer.WriteStartDocument(true);
            writer.WriteStartElement(type.Name);

            writer.WriteStartElement("Item");
            PropertyInfo[] properties = type.GetProperties();
            foreach (PropertyInfo property in properties)
            {
                if (property.GetCustomAttributes(typeof(StoreAttribute), true).Count() > 0 &&
                    property.GetValue(item, null) != null)
                {
                    writer.WriteAttributeString(property.Name, property.GetValue(item, null).ToString());
                }
            }
            writer.WriteEndElement();
            return "";
        }
    }
}
